import { _decorator, Component, Node, Touch, EventTouch, Vec2, NodeEventType, v3, Vec3, Quat } from 'cc';
import { GameManager } from '../../Scripts/Manager/GameManager';
import GameUI from '../../Scripts/UI/GameUI';
const { ccclass, property } = _decorator;

@ccclass('rotate')
export class rotate extends Component {
    private static instance: rotate;
    static get Instance() {
        return this.instance;
    }

    isMoving = false;
    isRotating = false;
    touchPos: Vec2;
    dir: Vec2;

    onLoad() {
        rotate.instance = this;
    }

    start() {
        this.node.on(NodeEventType.TOUCH_START, this.TouchStart, this);
        this.node.on(NodeEventType.TOUCH_MOVE, this.TouchMove, this);
        this.node.on(NodeEventType.TOUCH_END, this.TouchEnd, this);
        this.node.on(NodeEventType.TOUCH_CANCEL, this.TouchEnd, this);
    }

    update(deltaTime: number) {
    }

    TouchStart(event: EventTouch) {
        if (!GameManager.Instance.level) return;
        this.isRotating = true;
        this.touchPos = event.getLocation();
    }

    TouchMove(event: EventTouch) {
        if (GameUI.Instance.isFinish) return;
        if (GameManager.Instance.IsTips) {
            GameManager.Instance.IsTips = false;
            GameUI.Instance.hideTips();
        }
        var level = GameManager.Instance.level;
        if (!level || !this.touchPos) return;
        var pos = event.getLocation();
        this.dir = pos.subtract(this.touchPos).multiplyScalar(0.003);
        this.touchPos = event.getLocation();
        var rot = this.dir;
        var q = level.getWorldRotation();
        // var euler = v3();
        // q.getEulerAngles(euler);
        // var x = euler.x + rot.y;
        // var y = euler.y + rot.x;
        // if (x > 180) x -= 360;
        // else if (x < -180) x += 360;
        // if (y > 180) y -= 360;
        // else if (y < -180) y += 360;
        // level.setWorldRotationFromEuler(x, euler.y, euler.z);
        Quat.rotateAround(q, q, Vec3.RIGHT, -rot.y);
        Quat.rotateAround(q, q, Vec3.UP, rot.x);
        level.setWorldRotation(q);
    }

    TouchEnd(event: EventTouch) {
        if (!GameManager.Instance.level || !this.touchPos) return;
        this.isRotating = false;
        this.touchPos = null;
    }

    TouchOff() {
        this.node.off(NodeEventType.TOUCH_START, this.TouchStart, this);
        this.node.off(NodeEventType.TOUCH_MOVE, this.TouchMove, this);
        this.node.off(NodeEventType.TOUCH_END, this.TouchEnd, this);
        this.node.off(NodeEventType.TOUCH_CANCEL, this.TouchEnd, this);
    }
}

